package com.swpu.cbg.cnshop.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.squareup.okhttp.Response;
import com.swpu.cbg.cnshop.Constans;
import com.swpu.cbg.cnshop.R;
import com.swpu.cbg.cnshop.adapter.BaseAdapter;
import com.swpu.cbg.cnshop.adapter.CatagoryContentAdapter;
import com.swpu.cbg.cnshop.adapter.CatagoryLeftAdapter;
import com.swpu.cbg.cnshop.adapter.DividerItemDecortion;
import com.swpu.cbg.cnshop.bean.Banner;
import com.swpu.cbg.cnshop.bean.CatagoryLeftBean;
import com.swpu.cbg.cnshop.bean.PageContent;
import com.swpu.cbg.cnshop.bean.Ware;
import com.swpu.cbg.cnshop.http.OkHttpHelper;
import com.swpu.cbg.cnshop.http.SpotsCallback;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenboge on 16/1/30.
 */
public class CategoryFragment extends BaseFragment {

    private View mView;
    private LayoutInflater mInflater;
    private OkHttpHelper mHelper;
    private List<Banner> mBanners;
    private Gson mGson = new Gson();
    private List<CatagoryLeftBean> mLeftData;
    private CatagoryLeftAdapter<CatagoryLeftBean> mLCAdapter;
    private CatagoryContentAdapter<Ware> mCCAdapter;
    private List<Ware> mWares;

    private int CatagroyID = 1;
    private int curPage = 1;
    private int pageSize = 10;
    private int Totle_Page = 1;

    private static final int STATE_NORMAL = 0;
    private static final int STATE_REFRESH = 1;
    private static final int STATE_LOADMORE = 2;
    private int state = STATE_NORMAL;

    @ViewInject(R.id.slider)
    private SliderLayout sliderShow;

    @ViewInject(R.id.custom_indicator)
    private PagerIndicator mIndicater;

    @ViewInject(R.id.id_catagory_left_recyclerview)
    private RecyclerView mLeftRecyclerview;

    @ViewInject(R.id.id_catagory_refresh)
    private MaterialRefreshLayout mRefreshLayout;

    @ViewInject(R.id.id_catagory_content_recyclerview)
    private RecyclerView mContentRecyclerview;


    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mInflater = LayoutInflater.from(getActivity());
        mView = mInflater.inflate(R.layout.category, container, false);
        return mView;
    }

    @Override
    public void init() {
        mHelper = OkHttpHelper.getInstance();
        requestHeaderImageData();
        getCatagoryData();
        getCatagroyContentData(CatagroyID, curPage, pageSize);
        initRefreshLayout();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setLoadMore(true);
        mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {

            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                curPage = ++curPage;
                getCatagroyContentData(CatagroyID, curPage, pageSize);
                mRefreshLayout.finishRefreshLoadMore();
            }
        });
    }


    private void refreshData() {
        curPage = 1;
        state = STATE_REFRESH;
        getCatagroyContentData(CatagroyID, curPage, pageSize);
    }


    private void loadMOreData() {
        if (curPage <= Totle_Page) {
            curPage = ++curPage;
            state = STATE_LOADMORE;
            getCatagroyContentData(CatagroyID, curPage, pageSize);
        } else {
            Toast.makeText(getActivity(), "数据已加载到最后一页", Toast.LENGTH_SHORT).show();
            mRefreshLayout.finishRefreshLoadMore();
        }
    }

    private void getCatagroyContentData(int catagroyID, int curPage, int pageSize) {
        Map<String, Object> data = new HashMap<>();
        data.put("categoryId", CatagroyID + "");
        data.put("curPage", curPage + "");
        data.put("pageSize", pageSize + "");
        mHelper.post(Constans.API.CATAGORY_CONTENT_URL, data, new SpotsCallback<PageContent<Ware>>(getActivity()) {
            @Override
            public void onSuccess(Response response, PageContent<Ware> warePageContent) {
                mWares = warePageContent.getList();
                Totle_Page = warePageContent.getTotalPage();
                initContentRecyview();
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }

            @Override
            public void onTokenError(Response response, int code) {

            }
        });
    }

    private void initContentRecyview() {
        switch (state) {
            case STATE_NORMAL:
                if (mCCAdapter == null) {
                    mCCAdapter = new CatagoryContentAdapter<Ware>(getActivity(), mWares, R.layout.template_catagory_gridview);
                    mContentRecyclerview.setAdapter(mCCAdapter);
                    mContentRecyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 2));
                    mContentRecyclerview.addItemDecoration(new DividerItemDecortion());
                    mContentRecyclerview.setItemAnimator(new DefaultItemAnimator());
                } else {
                    mCCAdapter.ClearData();
                    mCCAdapter.AddData(mWares);

                }
                break;

            case STATE_REFRESH:
                mCCAdapter.ClearData();
                mCCAdapter.AddData(mWares);
                mContentRecyclerview.scrollToPosition(0);
                mRefreshLayout.finishRefresh();
                break;

            case STATE_LOADMORE:
                int itemSize = mCCAdapter.getDatas().size();
                mCCAdapter.AddData(itemSize, mWares);
                mContentRecyclerview.scrollToPosition(mCCAdapter.getDatas().size());
                mRefreshLayout.finishRefreshLoadMore();
                break;
        }

    }


    private void getCatagoryData() {
        mHelper.get(Constans.API.CATAGORY_LEFT_URL,null, new SpotsCallback<List<CatagoryLeftBean>>(getActivity()) {

            @Override
            public void onSuccess(Response response, List<CatagoryLeftBean> catagoryLeftBeans) {
                mLeftData = catagoryLeftBeans;
                initLeftRecyviewData();
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }

            @Override
            public void onTokenError(Response response, int code) {

            }

        });
    }


    public void initLeftRecyviewData() {
        mLCAdapter = new CatagoryLeftAdapter<CatagoryLeftBean>(getActivity(), mLeftData, R.layout.template_catagory_left_view);
        mLCAdapter.setOnItemClickListener(new BaseAdapter.onItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Toast.makeText(getActivity(), ((CatagoryLeftBean) mLeftData.get(position)).getName(), Toast.LENGTH_SHORT).show();
                CatagroyID = mLeftData.get(position).getSort();
                refreshData();
            }
        });
        mLeftRecyclerview.setAdapter(mLCAdapter);
        mLeftRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mLeftRecyclerview.setItemAnimator(new DefaultItemAnimator());
        mLeftRecyclerview.addItemDecoration(new DividerItemDecortion());
    }

    private void initSliderViewData() {

        if (mBanners != null) {
            for (Banner banner : mBanners) {

                TextSliderView textSliderView = new TextSliderView(getActivity());
                textSliderView
                        .description(banner.getName())
                        .image(banner.getImgUrl());
                //点击事件
                textSliderView.setScaleType(BaseSliderView.ScaleType.Fit);
                textSliderView.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                    @Override
                    public void onSliderClick(BaseSliderView slider) {


                    }
                });

                sliderShow.addSlider(textSliderView);
            }

        }

        //设置底部导航状态栏
        sliderShow.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        sliderShow.setCustomIndicator(mIndicater);

        sliderShow.setCustomAnimation(new DescriptionAnimation());
        sliderShow.setPresetTransformer(SliderLayout.Transformer.Accordion);
        sliderShow.setDuration(3000);

        sliderShow.addOnPageChangeListener(new ViewPagerEx.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    public void requestHeaderImageData() {
        Map<String, Object> data = new HashMap<>();
        data.put("type", "1");

        mHelper.post(Constans.API.HOME_TOP_URL, data, new SpotsCallback<List<Banner>>(getActivity()) {

            @Override
            public void onSuccess(Response response, List<Banner> banners) {
                mBanners = banners;
                initSliderViewData();
            }

            @Override
            public void onError(Response response, int code, Exception e) {
                throw new RuntimeException("网络出现异常");
            }

            @Override
            public void onTokenError(Response response, int code) {

            }
        });

    }

    @Override
    public void onStop() {
        sliderShow.stopAutoCycle();
        super.onStop();

    }
}
